package com.hjc.util;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: huangjc
 * @Date: Created in 2020-7-17 16:08
 */
public class ImageUtil {

	private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);

	/**
	 * 等比例压缩
	 *
	 * @param image
	 * @param os
	 * @return
	 */
	public static void compressImage(BufferedImage image, OutputStream os, String outputFormat) {
		try {
			Thumbnails.of(image).scale(0.5f).outputFormat(outputFormat).toOutputStream(os);
		} catch (IOException e) {
			logger.error("压缩图片异常", e);
		}
	}

	/**
	 * 等比例压缩
	 *
	 * @param srcFile
	 * @param distFilePath
	 * @return
	 */
	public static void compressImage(File srcFile, String distFilePath) {
		try {
			File file = new File(distFilePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			Thumbnails.of(srcFile).scale(0.5f).toFile(file);
		} catch (IOException e) {
			logger.error("压缩图片异常，distFilePath：{}", distFilePath, e);
		}
	}

	/**
	 * 等比例压缩
	 *
	 * @param srcFilePath
	 * @param distFilePath
	 * @return
	 */
	public static void compressImage(String srcFilePath, String distFilePath) {
		try {
			File file = new File(distFilePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			Thumbnails.of(srcFilePath).scale(0.5f).toFile(file);
		} catch (IOException e) {
			logger.error("压缩图片异常，distFilePath：{}", distFilePath, e);
		}
	}

	/**
	 * 压缩文件
	 *
	 * @param srcFilePath
	 * @param distFilePath
	 * @param newWidth
	 * @param newHeight
	 * @return
	 */
	public static void compressImage(String srcFilePath, String distFilePath, int newWidth, int newHeight) {
		try {
			File file = new File(distFilePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			Thumbnails.of(srcFilePath).size(newWidth, newHeight).toFile(file);
		} catch (IOException e) {
			logger.error("压缩图片异常，distFilePath：{}", distFilePath, e);
		}
	}

	public static void main(String[] args) {
		ImageUtil.compressImage("d://0.jpg", "d://1/3/2.jpg");
	}
}
